package com.soilflow.web.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soilflow.common.core.domain.entity.SysDept;
import com.soilflow.common.domain.LandInfo;
import com.soilflow.info.service.LandInfoService;
import com.soilflow.system.service.ISysDeptService;
import org.springframework.context.ApplicationContext;

import java.util.List;

/**
 * @author steven
 * @date 2024年01月03日 15:48:01
 */
public class LandNoUtils {

    public String genNoUtil(SysDept sysDept){

        String No = "#";

        ApplicationContext context = SpringBeanUtil.getApplicationContext();
        ISysDeptService deptService = context.getBean(ISysDeptService.class);

        // # +  镇1位 + 村2位 + 土地4
        // ancestors : 0,100,115
        String[] splitAncestors = sysDept.getAncestors().split(",");

        // 镇查询
        SysDept sysDeptZhen = new SysDept();
        sysDeptZhen.setParentId(Long.parseLong(splitAncestors[1]));
        List<SysDept> sysDeptsZhen = deptService.selectList(sysDeptZhen);
        for (int i = 0; i < sysDeptsZhen.size(); i++) {
            if (String.valueOf(sysDeptsZhen.get(i).getDeptId()).equals(splitAncestors[2])){
                No = No + (i+1);
                break;
            }
        }

        // 村查询
        SysDept sysDeptCun = new SysDept();
        System.out.println(splitAncestors[2]);
        sysDeptCun.setParentId(Long.parseLong(splitAncestors[2]));
        List<SysDept> sysDeptsCun = deptService.selectList(sysDeptCun);
        for (int i = 0; i < sysDeptsCun.size(); i++) {
            if (String.valueOf(sysDeptsCun.get(i).getDeptId()).equals(String.valueOf(sysDept.getDeptId()))){
                if ((i+1)>9){
                    No = No + (i+1);
                }else {
                    No = No + "0" + (i+1);
                }
                break;
            }
        }

        // 村有多少土地创建编号
        LandInfoService landInfoService = context.getBean(LandInfoService.class);
        QueryWrapper<LandInfo> landInfoQueryWrapper = new QueryWrapper<>();
        landInfoQueryWrapper.lambda().eq(LandInfo::getDeptId,sysDept.getDeptId());
        List<LandInfo> list = landInfoService.list(landInfoQueryWrapper);

        if (list.size()>9){
            No = No + "00" + (list.size()+1);
        }else if (list.size()>99){
            No = No + "0" + (list.size()+1);
        }else if (list.size()>999){
            No = No + (list.size()+1);
        }else {
            No = No + "000" + (list.size()+1);
        }

        return No;

    }

}
